#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

import imutils

from onnx_infer import infer

from PyQt5 import QtCore, QtGui, QtWidgets

resize = 0


from detect_ui import Ui_DetectWindow

import cv2
import sys
import numpy as np
from PyQt5.QtWidgets import *


from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw


def drawRectBox(image,rect,addText):
    font = ImageFont.truetype("simsun.ttc", 20, encoding="unic")
    cv2.rectangle(image, (int(rect[0]), int(rect[1])), (int(rect[2]), int(rect[3])), (34, 250, 21), 5,
                  cv2.LINE_AA)
    img = Image.fromarray(image)
    draw = ImageDraw.Draw(img)
    draw.text((int(rect[0])-50, int(rect[1])-50), addText.encode("utf-8").decode("utf-8"), (200, 200, 123), font)
    imagex = np.array(img)
    return imagex









class DetectWindow(QMainWindow, Ui_DetectWindow):
    def __init__(self, *args, **kwargs):
        super(DetectWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)  # 初始化ui
        self.is_cap = True


        self.showimage.setScaledContents(True)


        self.pushButton.clicked.connect(self.open_image)
        self.pushButton_2.clicked.connect(self.frame_detect)
        self.pushButton_exit.clicked.connect(self.close)

        self.showimage.setScaledContents(True)


        # self.lineEdit.show()

    def open_image(self):
        fileName1, filetype = QFileDialog.getOpenFileName(self,
                                                              "选取文件",
                                                              "./",
                                                              "All Files (*);;Image t Files (*.jpg)")



        self.frame_ = cv2.imread(fileName1)

        self.showimage.setPixmap(QtGui.QPixmap(fileName1))





    def frame_detect(self):
        self.trow = 0

        result = infer(self.frame_)



        result = imutils.resize(result, height=800)
        show = cv2.resize(result, (800,800))
        show2 = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)  # 视频色彩转换回RGB，这样才是现实的颜色
        showImage = QtGui.QImage(show2.data, show2.shape[1], show2.shape[0],
                                 QtGui.QImage.Format_RGB888)  # 把读取到的视频数据变成QImage形式
        self.showimage.setPixmap(QtGui.QPixmap.fromImage(showImage))  # 往显示视频的Label里 显示QImage


if __name__ == '__main__':  # 程序的入口
    app = QApplication(sys.argv)
    # app.setStyleSheet(qdarkstyle.load_stylesheet())
    win = DetectWindow()
    win.show()
    sys.exit(app.exec_())